package com.example.login.service.impl;

import com.example.common.constant.MessageConstant;
import com.example.common.exception.AccountNotFoundException;
import com.example.login.config.JwtProperties;
import com.example.login.domain.dto.EmployeeLoginCaptchaDTO;
import com.example.login.domain.dto.EmployeeLoginPasswordDTO;
import com.example.login.domain.dto.EmployeeRegisterDTO;
import com.example.login.domain.enums.EStatusEnum;
import com.example.login.domain.po.Employee;
import com.example.login.domain.vo.EmployeeLoginVO;
import com.example.login.mapper.AuthMapper;
import com.example.login.service.EmployeeAuthService;
import com.example.login.utils.JwtUtil;
import com.example.login.utils.SMSUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
@RequiredArgsConstructor
public class EmployeeAuthServiceImpl implements EmployeeAuthService {

    private final AuthMapper employeeMapper;
    private final JwtProperties jwtProperties;
    private final JwtUtil jwtUtil;
    private final SMSUtil smsUtil;

    @Value("${tree.employee.avatar}")
    private String avatar;

    /**
     * 员工验证码登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public EmployeeLoginVO loginByCaptcha(EmployeeLoginCaptchaDTO employeeLoginDTO) {
        smsUtil.checkCaptcha(employeeLoginDTO.getPhone(), employeeLoginDTO.getCaptcha());
        // 1.数据校验
        String phone = employeeLoginDTO.getPhone();
        // 2.根据手机号查询
        Employee employee = employeeMapper.selectEmployeeByPhone(phone);

        // 3.校验账号状态（用户不存在、密码不对、账号被锁定）
        if (employee == null) {
            // ACCOUNT_NOT_FOUND:账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (EStatusEnum.FROZEN == EStatusEnum.of(employee.getStatus())) {
            // ACCOUNT_LOCKED:账号被锁定
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }
        // 5.生成TOKEN
        // jwt 数据部分
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", employee.getId());
        claims.put("role", employee.getRole());
        String token = jwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtlMillis(), claims);
        // 6.封装VO返回
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .token(token)
                .phone(employee.getPhone())
                .nickname(employee.getNickname())
                .avatar(employee.getAvatar())
                .build();
        return employeeLoginVO;
    }

    /**
     * 员工密码登录
     *
     * @param employeeLoginPasswordDTO
     * @return
     */
    @Override
    public EmployeeLoginVO loginByPassword(EmployeeLoginPasswordDTO employeeLoginPasswordDTO) {
        // 1.数据校验
        String phone = employeeLoginPasswordDTO.getPhone();
        String password = employeeLoginPasswordDTO.getPassword();
        // 2.根据手机号查询
        Employee employee = employeeMapper.selectEmployeeByPhone(phone);

        // 3.校验账号状态（用户不存在、密码不对、账号被锁定）
        if (employee == null) {
            // ACCOUNT_NOT_FOUND:账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (EStatusEnum.FROZEN == EStatusEnum.of(employee.getStatus())) {
            // ACCOUNT_LOCKED:账号被锁定
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_LOCKED);
        }
        // 4.校验密码
        // 密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            // PASSWORD_ERROR:密码错误
            throw new AccountNotFoundException(MessageConstant.PASSWORD_ERROR);
        }

        // 5.生成TOKEN
        // jwt 数据部分
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", employee.getId());
        claims.put("role", employee.getRole());
        String token = jwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtlMillis(), claims);
        // 6.封装VO返回
        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .token(token)
                .phone(employee.getPhone())
                .nickname(employee.getNickname())
                .avatar(employee.getAvatar())
                .build();
        return employeeLoginVO;
    }

    /**
     * 员工注册
     *
     * @param employeeRegisterDTO
     */
    @Override
    public void register(EmployeeRegisterDTO employeeRegisterDTO) {
        String phone = employeeRegisterDTO.getPhone();
        String captcha = employeeRegisterDTO.getCaptcha();
        String password = employeeRegisterDTO.getPassword();
        // 验证验证码是否正确
         smsUtil.checkCaptcha(phone, captcha);

        Employee employee= Employee.builder()
                .nickname(phone)
                .phone(phone)
                .password(DigestUtils.md5DigestAsHex(password.getBytes()))
                .avatar(avatar)
                .gender(1)
                .status(1)
                .role(1)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();


        employeeMapper.register(employee);

    }

    /**
     * 校验手机号是否被注册
     *
     * @param phone
     * @return
     */
    @Override
    public Boolean checkPhone(String phone) {
        Employee employee = employeeMapper.selectEmployeeByPhone(phone);
        return employee == null;
    }
}
